package com.gel.codegeneration.common.aop;

import com.gel.codegeneration.common.Annotation.AuthCheck;
import com.gel.codegeneration.common.enums.ErrorCode;
import com.gel.codegeneration.common.enums.UserRoleEnum;
import com.gel.codegeneration.convention.exception.BusinessException;
import com.gel.codegeneration.model.entity.User;
import com.gel.codegeneration.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import static com.gel.codegeneration.common.constant.UserConstant.USER_LOGIN_KEY;

/**
 * @BelongsProject: code-generation-platform
 * @BelongsPackage: com.gel.codegeneration.common.aop
 * @Author: gel
 * @CreateTime: 2025-08-21  14:33
 * @Description: TODO 权限认证拦截器（aop+annotation）
 * @Version: 1.0
 */
@Aspect
@Component
public class AuthInterceptor {

    @Resource
    private UserService userService;
    @Around("@annotation(authCheck)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        String mustRole = authCheck.mustRole();
        //获取当前登录用户
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request =((ServletRequestAttributes)requestAttributes).getRequest();
        User user =userService.getLoginUser( request);
        if(user==null){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        UserRoleEnum mustRoleEnum = UserRoleEnum.getEnumByValue(mustRole);
        //不需要权限，均放行
        if(mustRoleEnum==null){
           return joinPoint.proceed();
        }
        //需要权限
        UserRoleEnum userRoleEnum = UserRoleEnum.getEnumByValue(user.getUserRole());
        //没有权限，拒绝
        if(userRoleEnum==null){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        //煤油
        if(UserRoleEnum.ADMIN.equals(mustRoleEnum)&&!UserRoleEnum.ADMIN.equals(userRoleEnum)){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        return joinPoint.proceed();


    }
}
